package com.payge.firework.screens

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.dp
import com.payge.firework.R
import com.payge.firework.model.Firecracker
import com.payge.firework.model.Particle
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.random.Random

/**
 * 仿现实生活中放烟花特效
 */
@Composable
fun InteractiveFireworksEffect(
    modifier: Modifier = Modifier,
    particleCount: Int = 150,
    minParticleSize: Float = 3f,
    maxParticleSize: Float = 9f,
    firecrackerSize: Float = 9f,
    width: Int, height: Int
) {
    var fireworks by remember { mutableStateOf(emptyList<Firecracker>()) }
    var explosions by remember { mutableStateOf(emptyList<List<Particle>>()) }
    var nextFirecrackerId by remember { mutableIntStateOf(0) }

    // 定时生成新的花炮
    LaunchedEffect(Unit) {
        while (isActive) {
            val times = Random.nextInt(4, 10)
            repeat(times) {
                // 随机水平位置生成新花炮
                val x = Random.nextFloat() * (width - 200.dp.value) + 100.dp.value
                // 随机目标高度
                val targetY = Random.nextFloat() * (height / 3) + height / 4
                fireworks = fireworks + Firecracker(
                    id = nextFirecrackerId++,
                    x = x,
                    y = height - 200.dp.value, // 从底部开始
                    targetY = targetY,
                    color = when (Random.nextInt(6)) {
                        0 -> Color(0xFFFF5252) // 红
                        1 -> Color(0xFFFFEB3B) // 黄
                        2 -> Color(0xFF4CAF50) // 绿
                        3 -> Color(0xFF2196F3) // 蓝
                        4 -> Color(0xFF9C27B0) // 紫
                        else -> Color(0xFFFF9800) // 橙
                    }
                )
                delay(300)
            }
            
            // 过滤掉已完成的花炮
            fireworks = fireworks.filter { !it.isFinished }
            
            delay(3000) // 每几秒生成多个新花炮
        }
    }

    // 更新花炮位置（上升动画）
    LaunchedEffect(fireworks) {
        while (isActive) {
            fireworks = fireworks.map { firecracker ->
                if (firecracker.isExploding || firecracker.isFinished) {
                    return@map firecracker
                }
                
                // 花炮上升，速度逐渐减慢（模拟重力影响）
                val progress = 1 - (firecracker.y / height * 1.1f)
                val speed = 8 * (1 - progress * 0.8f)
                var newY = firecracker.y - speed
                
                // 更新尾迹
                val newTrail = (listOf(Offset(firecracker.x, firecracker.y)) + firecracker.trail)
                    .take(30) // 只保留最近的30个点
                
                // 如果到达目标高度，自动爆炸
                if (newY <= firecracker.targetY) {
                    newY = firecracker.targetY
                    // 创建爆炸效果
                    val explosion = createExplosion(
                        centerX = firecracker.x,
                        centerY = newY,
                        particleCount = particleCount,
                        minSize = minParticleSize,
                        maxSize = maxParticleSize,
                        baseColor = firecracker.color
                    )
                    explosions = explosions + listOf(explosion)
                    return@map firecracker.copy(
                        y = newY,
                        isExploding = true,
                        trail = newTrail
                    )
                }
                
                firecracker.copy(y = newY, trail = newTrail)
            }
            
            delay(16) // 约60fps
        }
    }

    // 更新爆炸粒子状态
    LaunchedEffect(explosions) {
        while (isActive) {
            // 更新所有粒子的物理状态
            explosions = explosions.map { particles ->
                particles.mapNotNull { particle ->
                    // 更新粒子生命
                    particle.life -= 0.015f
                    if (particle.life <= 0) {
                        return@mapNotNull null
                    }

                    // 应用重力 (模拟向下的加速度)
                    particle.velocityY += 0.15f

                    // 应用空气阻力 (速度逐渐减慢)
                    particle.velocityX *= 0.98f
                    particle.velocityY *= 0.98f

                    // 更新位置
                    particle.x += particle.velocityX
                    particle.y += particle.velocityY

                    // 更新旋转
                    particle.rotation += particle.rotationSpeed

                    particle
                }
            }.filter { it.isNotEmpty() } // 过滤掉已经没有粒子的爆炸
            
            // 标记已爆炸完成的花炮
            fireworks = fireworks.map { firecracker ->
                if (firecracker.isExploding && 
                    explosions.none { explosion -> 
                        explosion.any { it.x == firecracker.x && it.y == firecracker.y }
                    }) {
                    firecracker.copy(isFinished = true, isExploding = false)
                } else {
                    firecracker
                }
            }
            
            delay(16) // 约60fps
        }
    }

    // 处理点击事件
    fun handleFirecrackerTap(x: Float, y: Float) {
        fireworks.forEachIndexed { index, firecracker ->
            if (!firecracker.isExploding && !firecracker.isFinished) {
                // 计算点击位置与花炮的距离
                val distance = sqrt(
                    (x - firecracker.x).pow(2) + (y - firecracker.y).pow(2)
                )
                
                // 如果点击在花炮附近
                if (distance < firecrackerSize * 8) {
                    // 创建爆炸效果
                    val explosion = createExplosion(
                        centerX = firecracker.x,
                        centerY = firecracker.y,
                        particleCount = particleCount,
                        minSize = minParticleSize,
                        maxSize = maxParticleSize,
                        baseColor = firecracker.color
                    )
                    explosions = explosions + listOf(explosion)
                    
                    // 更新花炮状态
                    fireworks = fireworks.mapIndexed { i, f ->
                        if (i == index) f.copy(isExploding = true) else f
                    }
                }
            }
        }
    }

    // 绘制夜空背景的闪烁星星
    val starOpacity = remember { Animatable(0.5f) }
    LaunchedEffect(Unit) {
        starOpacity.animateTo(
            targetValue = 1f,
            animationSpec = infiniteRepeatable(
                animation = tween(1000, easing = LinearEasing),
                repeatMode = RepeatMode.Reverse
            )
        )
    }

    Box(
        modifier = modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures { tapOffset ->
                    handleFirecrackerTap(tapOffset.x, tapOffset.y)
                }
            }
    ) {
        // 绘制夜空和星星
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawRect(Color.Black)
            
            // 绘制随机星星
            repeat(100) {
                val starX = Random.nextFloat() * size.width
                val starY = Random.nextFloat() * size.height
                val starSize = Random.nextFloat() * 1.5f + 0.5f
                drawCircle(
                    color = Color.White.copy(alpha = starOpacity.value * (Random.nextFloat() * 0.5f + 0.5f)),
                    radius = starSize,
                    center = Offset(starX, starY)
                )
            }
        }

        // 绘制花炮尾迹
        Canvas(modifier = Modifier.fillMaxSize()) {
            fireworks.forEach { firecracker ->
                if (!firecracker.isExploding && !firecracker.isFinished && firecracker.trail.size > 1) {
                    // 绘制尾迹线
                    for (i in 0 until firecracker.trail.size - 1) {
                        val alpha = 1f - (i.toFloat() / firecracker.trail.size) * 0.8f
                        drawLine(
                            color = firecracker.color.copy(alpha = alpha),
                            start = firecracker.trail[i],
                            end = firecracker.trail[i + 1],
                            strokeWidth = 4f
                        )
                    }
                }
            }
        }

        val image = ImageBitmap.imageResource(R.mipmap.firework)
        // 绘制花炮实体
        Canvas(modifier = Modifier.fillMaxSize()) {
            fireworks.forEach { firecracker ->
                if (!firecracker.isExploding && !firecracker.isFinished) {
                    // 绘制花炮主体
                    drawCircle(
                        color = firecracker.color,
                        radius = firecrackerSize,
                        center = Offset(firecracker.x, firecracker.y)
                    )
                    
                    // 绘制花炮头部光晕
                    drawCircle(
                        color = firecracker.color.copy(alpha = 0.5f),
                        radius = firecrackerSize * 1.5f,
                        center = Offset(firecracker.x, firecracker.y)
                    )

                    scale(
                        scale = 0.5f,
                        pivot = Offset(firecracker.x - image.width / 4,
                            height - image.height / 4f - 300.dp.value)
                    ) {
                        // 花炮图
                        drawImage(
                            image,
                            topLeft = Offset(
                                firecracker.x - image.width / 4,
                                height - image.height / 4f - 300.dp.value
                            ),
                        )
                    }
                }
            }
        }

        // 绘制所有爆炸粒子
        Canvas(modifier = Modifier.fillMaxSize()) {
            explosions.forEach { particles ->
                particles.forEach { particle ->
                    drawParticle(particle)
                }
            }
        }
    }
}

// 创建一次爆炸的所有粒子，基于花炮颜色生成相近色
private fun createExplosion(
    centerX: Float,
    centerY: Float,
    particleCount: Int,
    minSize: Float,
    maxSize: Float,
    baseColor: Color? = null
): List<Particle> {
    return List(particleCount) {
        // 随机角度和速度
        val angle = Random.nextFloat() * 2 * Math.PI.toFloat()
        val speed = Random.nextFloat() * 6f + 2f
        
        // 计算速度分量
        val velocityX = cos(angle).toFloat() * speed
        val velocityY = sin(angle).toFloat() * speed
        
        // 随机大小
        val radius = Random.nextFloat() * (maxSize - minSize) + minSize
        
        // 颜色 - 基于基础颜色生成相近色
        val color = baseColor?.let {
            var hsv = floatArrayOf(0f, 0f, 0f)
            android.graphics.Color.colorToHSV(it.toArgb(), hsv)
            val hue = (hsv[0] + (Random.nextFloat() * 30f - 15f)).mod(360f)
            Color.hsv(hue, hsv[1], hsv[2])
        } ?: when (Random.nextInt(6)) {
            0 -> Color(0xFFFF5252) // 红
            1 -> Color(0xFFFFEB3B) // 黄
            2 -> Color(0xFF4CAF50) // 绿
            3 -> Color(0xFF2196F3) // 蓝
            4 -> Color(0xFF9C27B0) // 紫
            else -> Color(0xFFFF9800) // 橙
        }
        
        // 随机生命周期和旋转
        val maxLife = Random.nextFloat() * 0.5f + 1.0f
        
        Particle(
            x = centerX,
            y = centerY,
            velocityX = velocityX,
            velocityY = velocityY,
            radius = radius,
            color = color,
            life = maxLife,
            maxLife = maxLife,
            rotation = Random.nextFloat() * 360f,
            rotationSpeed = Random.nextFloat() * 10f - 5f
        )
    }
}

// 绘制单个粒子
private fun DrawScope.drawParticle(particle: Particle) {
    // 随着生命减少，粒子逐渐变暗、变小
    val alpha = particle.life / particle.maxLife
    val currentSize = particle.radius * alpha
    
    drawCircle(
        color = particle.color.copy(alpha = alpha),
        radius = currentSize,
        center = Offset(particle.x, particle.y)
    )
    
    // 绘制粒子尾迹，增强视觉效果
    if (alpha > 0.3f) {
        drawCircle(
            color = particle.color.copy(alpha = alpha * 0.3f),
            radius = currentSize * 1.5f,
            center = Offset(
                particle.x - particle.velocityX * 2,
                particle.y - particle.velocityY * 2
            )
        )
    }
}
